package org.dromara.tearoom.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.tearoom.domain.TerGroupBuy;
import org.dromara.tearoom.domain.TerUser;
import org.dromara.tearoom.domain.bo.TerGroupBuyBo;
import org.dromara.tearoom.domain.enums.GroupBuyStateEnum;
import org.dromara.tearoom.domain.vo.TerGroupBuyTotalVo;
import org.dromara.tearoom.domain.vo.TerGroupBuyVo;
import org.dromara.tearoom.domain.vo.TerUserVo;
import org.dromara.tearoom.mapper.TerGroupBuyMapper;
import org.dromara.tearoom.mapper.TerUserMapper;
import org.dromara.tearoom.service.ITerGroupBuyService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 团购核销Service业务层处理
 *
 * @author ckj
 * @date 2025-05-08
 */
@RequiredArgsConstructor
@Service
public class TerGroupBuyServiceImpl implements ITerGroupBuyService {

    private final TerGroupBuyMapper baseMapper;
    private final TerUserMapper terUserMapper;

    /**
     * 查询团购核销
     *
     * @param id 主键
     * @return 团购核销
     */
    @Override
    public TerGroupBuyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询团购核销
     *
     * @param id 主键
     * @return 团购核销
     */
    @Override
    public TerGroupBuy queryEntityById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 查询团购核销
     *
     * @param encryptedCode 加密劵码
     * @return 团购核销
     */
    @Override
    public TerGroupBuy queryByEncryptedCode(String encryptedCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<TerGroupBuy>().eq(TerGroupBuy::getEncryptedCode,encryptedCode));
    }

    /**
     * 查询团购核销
     *
     * @param code 加密劵码
     * @return 团购核销
     */
    @Override
    public TerGroupBuy queryByCode(String code) {
        return baseMapper.selectOne(new LambdaQueryWrapper<TerGroupBuy>().eq(TerGroupBuy::getCode,code));
    }

    /**
     * 分页查询团购核销列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 团购核销分页列表
     */
    @Override
    public TableDataInfo<TerGroupBuyVo> queryPageList(TerGroupBuyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TerGroupBuy> lqw = buildQueryWrapper(bo);
        Page<TerGroupBuyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().stream().forEach(item->{
            if (!GroupBuyStateEnum.isUsed(item.getStatus())){
                item.setCode(DesensitizedUtil.address(item.getCode(),4));
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 统计团购数据
     *
     * @param bo
     * @return
     */
    @Override
    public List<TerGroupBuyTotalVo> total(TerGroupBuyBo bo) {
        return baseMapper.totalDataByDate(bo.getStartTime(),bo.getExpireTime());
    }

    /**
     * 查询符合条件的团购核销列表
     *
     * @param bo 查询条件
     * @return 团购核销列表
     */
    @Override
    public List<TerGroupBuyVo> queryList(TerGroupBuyBo bo) {
        LambdaQueryWrapper<TerGroupBuy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TerGroupBuy> buildQueryWrapper(TerGroupBuyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TerGroupBuy> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(TerGroupBuy::getCreateTime);
        lqw.eq(bo.getRelateId() != null, TerGroupBuy::getRelateId, bo.getRelateId());
        lqw.eq(bo.getCode() != null, TerGroupBuy::getCode, bo.getCode());
        lqw.eq(bo.getPlateOrderId() != null, TerGroupBuy::getPlateOrderId, bo.getPlateOrderId());
        lqw.eq(bo.getRelateType() != null, TerGroupBuy::getRelateType, bo.getRelateType());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TerGroupBuy::getName, bo.getName());
        lqw.eq(bo.getUserId() != null, TerGroupBuy::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getAccountId()), TerGroupBuy::getAccountId, bo.getAccountId());
        lqw.eq(bo.getStatus() != null, TerGroupBuy::getStatus, bo.getStatus());
        lqw.eq(bo.getPlateType() != null, TerGroupBuy::getPlateType, bo.getPlateType());
        if (ObjectUtil.isNotEmpty(params.get("userName"))) {
            List<TerUserVo> terUserVoList = terUserMapper.selectVoList(new LambdaQueryWrapper<TerUser>().like(TerUser::getNickname,params.get("userName")));
            if (CollUtil.isNotEmpty(terUserVoList)) {
                List<Long> memberUserIds = terUserVoList.stream().map(m -> m.getId()).collect(Collectors.toList());
                lqw.in(TerGroupBuy::getUserId, memberUserIds);
            } else {
                lqw.eq(TerGroupBuy::getUserId, 0L);
            }
        }
        if (ObjectUtil.isNotEmpty(params.get("userMobile"))) {
            List<TerUserVo> terUserVoList = terUserMapper.selectVoList(new LambdaQueryWrapper<TerUser>().like(TerUser::getMobile,params.get("userMobile")));
            if (CollUtil.isNotEmpty(terUserVoList)) {
                List<Long> memberUserIds = terUserVoList.stream().map(m -> m.getId()).collect(Collectors.toList());
                lqw.in(TerGroupBuy::getUserId, memberUserIds);
            } else {
                lqw.eq(TerGroupBuy::getUserId, 0L);
            }
        }
        if (ObjectUtil.isNotEmpty(params.get("useTimes"))) {
            List<String> createTimes = StrUtil.splitTrim(params.get("useTimes").toString(), ',');
            String startTime = createTimes.get(0);
            String endTime = createTimes.get(1);
            lqw.between(TerGroupBuy::getUseTime, startTime, endTime);
        }
        return lqw;
    }

    /**
     * 新增团购核销
     *
     * @param bo 团购核销
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TerGroupBuyBo bo) {
        TerGroupBuy add = MapstructUtils.convert(bo, TerGroupBuy.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量新增团购核销
     *
     * @param bo 团购核销
     * @return 是否新增成功
     */
    @Override
    public Boolean insertBatchByBo(List<TerGroupBuyBo> bo) {
        List<TerGroupBuy> filteredList = new ArrayList<>();
        for (TerGroupBuyBo item : bo) {
            LambdaQueryWrapper<TerGroupBuy> lqw = Wrappers.lambdaQuery();
            if(ObjectUtil.isNotEmpty(item.getCode())){
                lqw.eq(TerGroupBuy::getCode, item.getCode());
            }else{
                lqw.eq(TerGroupBuy::getEncryptedCode, item.getEncryptedCode());
            }
            TerGroupBuy buy=baseMapper.selectOne(lqw);
            if (ObjectUtil.isNotEmpty(buy)) {
                baseMapper.deleteById(buy.getId());
            }
            filteredList.add(MapstructUtils.convert(item, TerGroupBuy.class));
        }
        return baseMapper.insertBatch(filteredList);
    }

    /**
     * 修改团购核销
     *
     * @param bo 团购核销
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TerGroupBuyBo bo) {
        TerGroupBuy update = MapstructUtils.convert(bo, TerGroupBuy.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改团购核销
     *
     * @param buy 团购核销
     * @return 是否修改成功
     */
    @Override
    public Boolean updateById(TerGroupBuy buy) {
        return baseMapper.updateById(buy)>0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TerGroupBuy entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除团购核销信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


}
